#include "trayicon.h"
#include <QDebug>
#include <QAction>
#include <QApplication>
#include <QWidget>


TrayIcon::TrayIcon(QObject *parent) : QObject(parent)
{
    /* 图片闪烁，主要是用于消息提醒，通过定时器控制 */
    blink_timer = new QTimer;
    connect(blink_timer,SIGNAL(timeout()),this,SLOT(slot_changeIcon()));

    /* 创建右键菜单栏 */
    menu =new QMenu((QWidget*)QApplication::desktop());
    menu->setTitle("DPM 设置");

    QAction * showAction =new QAction(this);
    showAction->setText("显示");
    menu->setActiveAction(showAction);

    QAction * exitAction =new QAction(this);
    exitAction->setText("退出");
    menu->setActiveAction(exitAction);





    /* 创建系统托盘 */
    system_tray = new QSystemTrayIcon(this);
    connect(system_tray,SIGNAL(activated(QSystemTrayIcon::ActivationReason)),this,SLOT(activeTray(QSystemTrayIcon::ActivationReason)));
    /* 将右键菜单加入系统托盘 */
    system_tray->setContextMenu(menu);
    /* 设置系统托盘悬浮提示 */
    system_tray ->setToolTip(QString("欢迎使用 DPM V1.0 "));
    /* 设置系统托盘图标，没有这个不能正常显示 */
    system_tray ->setIcon(QIcon(":/images/v1.png"));
    system_tray->show();


}
void TrayIcon::init(){

}
///
/// \brief TrayIcon::setToolTip
/// \param msg
///提示内容
void TrayIcon::setToolTip(QString msg){
    system_tray ->setToolTip(msg);
}

///
/// \brief TrayIcon::stop_blink
///停止闪烁
void TrayIcon::stop_blink(){
    if(blink_timer->isActive())
        blink_timer->stop();
}
///
/// \brief TrayIcon::start_blink
///开始闪烁
void TrayIcon::start_blink(){
    stop_blink();
    blink_timer->start(1000);
}

///
/// \brief TrayIcon::setIcon
/// \param part
///设备图标
void TrayIcon::setIcon(QString part){
    system_tray ->setIcon(QIcon(part));
}


///
/// \brief TrayIcon::slot_changeIcon
///闪烁时间调度
void TrayIcon::slot_changeIcon()
{
    static bool isNormal = false;
    if(isNormal){
        isNormal = false;
        setIcon(dis_icon);
    }else{
        isNormal = true;
        setIcon(active_icon);
    }
}

///
/// \brief TrayIcon::activeTray
/// \param reason
///托盘事件
void  TrayIcon::activeTray(QSystemTrayIcon::ActivationReason reason){
    qDebug()<< reason;

    switch (reason) {
    case QSystemTrayIcon::Context:
        menu->show();
        break;
    case QSystemTrayIcon::Trigger:
        break;
    case QSystemTrayIcon::DoubleClick:
         showWindow();
        break;
    }
}
void TrayIcon::showWindow(){
     QList<QObject*> o= engine->rootObjects();
             o.at(0)->setProperty("visible",true);
}
void TrayIcon::hidenWindow(){
    QList<QObject*> o= engine->rootObjects();
            o.at(0)->setProperty("visible",false);
}
